package de.gbeine.java.depview.graph;

import java.util.Set;

import lombok.extern.slf4j.Slf4j;
import de.gbeine.java.depview.model.Element;
import de.gbeine.java.depview.model.Package;
import edu.uci.ics.jung.graph.DirectedSparseMultigraph;
import edu.uci.ics.jung.graph.Graph;

@Slf4j
class PackageGraph implements GraphConverter {

    public static final PackageGraph INSTANCE = new PackageGraph();

    private PackageGraph() {
        super();
    }

    @Override
    public Graph<Element, Number> createGraph(final Set<Package> pModel, final Filter pFilter) {
        final Dependencies dependencies = new Dependencies();
        final Graph<Element, Number> graph = new DirectedSparseMultigraph<Element, Number>();
        int counter = 0;
        for (final Package pkg : pModel) {
            if (pFilter.isFiltered(pkg)) {
                PackageGraph.log.debug("Not adding package {} - it is filtered", pkg.getName());
                continue;
            }
            PackageGraph.log.debug("Try to add package {}", pkg.getName());
            for (final Package dep : pkg.outboundDependencies()) {
                PackageGraph.log.debug("Found dependency to {}", dep.getName());
                if (!pFilter.isFiltered(dep) && !dependencies.dependencyExists(pkg, dep)) {
                    PackageGraph.log.debug("Add package {}", pkg.getName());
                    dependencies.addDependency(pkg, dep);
                    graph.addEdge(counter, pkg, dep);
                    counter++;
                }
            }
        }
        return graph;
    }

}
